﻿window.onload = function() {
	temp = null;
	tempHeight = 0;
	pc_userinfo = null;
	userId = null;
	cardWrap = $('<div>').addClass('personcard-wrap');
	$('body').append(cardWrap);
	bigWrap = $('.personcard-wrap');

	bindHoverCard();
}

function bindHoverCard() {
	var isHover = false;
	var showHoverCard, removeHoverCard, currentCard;
	var hoverDelay = null;

	$('.person').live('mouseover', function () {
		var that = $(this);
		hoverDelay = setTimeout(function() {
			personHeight = that.height();
			personWidth = that.width();
			pageX = that.offset().left;
			pageY = that.offset().top - $(document).scrollTop();
			if(currentCard) currentCard.remove();
			if(removeHoverCard) clearTimeout(removeHoverCard);
			if(showHoverCard) clearTimeout(showHoverCard);
			userId = that.attr('data-id');

			// 显示名片
			showHoverCard = setTimeout(hoverCardBuilder(userId, that), 300);
		}, 500);
		$('.person').click(function () {
		    leave();
	    });
	});

	$('.person').live('mouseleave', function () {
	    leave();
	});

	// 删除名片
	removeCard = function() {
		removeHoverCard = setTimeout(function() {
			bigWrap.hide(100); // 里面元素没有移除，只是隐藏
		}, 600);
	}

	hoverCardBuilder = function(id, hoverObject) {
		if(!isHover) {
			isHover = true;
			bigWrap.attr('class', 'personcard-wrap');
			// 插入DOM
			var cardContent = $('<div>').addClass('personcard-content');

			var personCard = '';
			personCard += '<div class="personcard"><div class="bgbox card-bgbox"></div><div class="mask_box"></div> <div class="personcard_contentbox"><div class="personcard"><div class="pic_box"><a target="_blank" href="#"><img class="img_y card-avatar" width="50" height="50" alt=""></a><a href="#" class="icon_bed"><i class="icon new_status card-userType"></i></a></div>'; //这里img src要动态获取
			personCard += '<div class="mask"><div class="name"><a target="_blank" href="#" class="nickname nickname1 W_autocut card-nick"></a><div class="account_pull_box js_account_pull multi-account" style="line-height:0;"><span class="card-box account_num_bg_box"></span></div><img class="card-brokeId" alt=""><i class="sex_icon"></i></div> </div></div>'; // 这里nickname，和i 是动态获取

			var personFoot = '';
			personFoot += '<div class="person-foot">'; // 这里如果是普通用户或交易员会有 numrow3/numrow4
			personFoot += '<div class="person_follow"><div class="setfollow"> <div class="user_interact_box interactBtn_wrap">';
			personFoot += '<ul class="clearfix"><li class="focus-li pr"><a href="javascript:;" class="interactFocus interactBtn"><span></span></a><div class="drop_menu_list" style="display: none;"><ul><li><a href="javascript:;">取消关注</a></li></ul></div></li><li class="ml5"></li></ul></div> </div>'; // 这里是私信关注			
			personFoot += '<a href="#" target="_blank" class="focus_num numlink">关注<em>0</em>人</a><a href="#" target="_blank" class="fans_num numlink">粉丝<em>0</em>人</a></div>';
			personFoot += '</div>';

			var personArrow = '<div class="personcard_arrow"><span class="box_arrow box_arrow_t"><i class="sline"></i><em class="sbg"></em></span></div>';
			id1 = hoverObject.attr('data-id');

			if(typeof(id1) == "string") {

				cardContent.append(personCard).append(personFoot).append(personArrow);
				cardWrap.append(cardContent);

				if(temp !== id1) {
					tempHeight = bigWrap.height();
					ajax(id1);
				}
				// 用户昵称
				$('.card-nick').html(pc_userinfo.NickName);
				// 用户头像
				$('.pic_box>a').attr('href', '/UserPage/' + id1);
				$('.card-avatar').attr('src', '/Avata/' + pc_userinfo.UserId).attr('alt', pc_userinfo.NickName);
				$('.nickname1').attr('href', '/UserPage/' + id1);
				// 用户头像背景
				$('.card-bgbox').css('background', 'url(' + '/Avata/' + pc_userinfo.UserId + ')' + ' no-repeat').css('background-position', 'center -310px').css('background-size', '220%');
				// 经纪商id为3 图标不显示
				if(pc_userinfo.BrokerId === 3) {
					$('.card-brokeId').css('display', 'none');
				} else {
					$('.card-brokeId').attr('src', '/Themes/DefaultClean/Images/broker/' + pc_userinfo.BrokerId + '.png');
				}
				// 关注私信部分
				var interactBtn = $('.interactFocus');
				var interactSpan = interactBtn.children('span');

                // 社区不显示关注按钮
                if (window.location.href.indexOf('social') > 0) {
				    $('.focus-li').hide();
				} 
				switch(pc_userinfo.AttentState) {
					case 1:
						interactBtn.attr('class', 'interactFocus interactBtn interactBtn_follow');
						interactSpan.attr('class', 'set_follow').html('<i></i>关注');
						$('.drop_menu_list').hide();
						$('.interactBtn_follow').click(function() {
							attentionUser(pc_userinfo.UserId);
						});
						break;
					case 2:
						interactBtn.attr('class', 'interactFocus interactBtn interactBtn_follow_mutual drop_icon');
						interactSpan.attr('class', 'follow_mutual').html('<i></i>互相关注');
						break;
					case 3:
						interactBtn.attr('class', 'interactFocus interactBtn interactBtn_follow_already drop_icon');
						interactSpan.attr('class', 'follow_already').html('<i></i>已关注');
						break;
					case 4:
						$('.user_interact_box').hide();
						break;
					default:
						interactBtn.attr('class', 'interactFocus interactBtn interactBtn_follow');
						interactSpan.attr('class', 'set_follow').html('<i></i>关注');
						interactBtn.click(function() {
							attentionUser(pc_userinfo.UserId);
						});
						break;
				}

				var a = pc_userinfo.AccountIndex;
				if(a > 10) {
					$('.card-box').addClass('account_num_bg_box' + a);
				} else {
					$('.card-box').addClass('account_num_bg_box0' + a);
				}
				// 用户性别是否显示
				if(pc_userinfo.IsShowGender) {
					// 用户性别
					if(pc_userinfo.Gender === 0) {
						$('.sex_icon').addClass('sex_icon_man');
					} else if(pc_userinfo.Gender === 1) {
						$('.sex_icon').addClass('sex_icon_women');
					}
				} else {
					$('.sex_icon').css('display', 'none');
				}

				// 关注数量
				$('.focus_num').attr('href', "/Member/Customer/Social_Home?id=" + id1 + "&tab=1");
				$('.focus_num em').html(pc_userinfo.AttentionCount);
				// 粉丝数量
				$('.fans_num').attr('href', "/Member/Customer/Social_Home?id=" + id1 + "&tab=2");
				$('.fans_num em').html(pc_userinfo.FansCount);
				var info = $('<div>');
				var userType = pc_userinfo.UserType;
				var accountRole = pc_userinfo.AccountRole;

				// 用户类型
				if(userType === 0) { // 模拟用户
					role(accountRole, id1);
					if(pc_userinfo.Expire == 0) { // 未失效					
						$('.card-userType').addClass('status-ordinary').attr('title', '普通用户');
					} else {
						$('.icon_bed').css('display', 'none');
					}
					$('.person_follow').before(info.addClass('person_intro').html('个人简介：' + pc_userinfo.Introduction));
				} else if(userType === 1) { // 交易员	
					$('.focus_num').attr('href', "/Member/Trader/Social_Home?id=" + id1 + "&tab=1");
					$('.fans_num').attr('href', "/Member/Trader/Social_Home?id=" + id1 + "&tab=2");
					role(accountRole, id1);
					// 是否显示交易信息
					showTrade(pc_userinfo.IsShowTrade, '交易策略：', pc_userinfo.StrategyDescription, info);
					$('.card-userType').addClass('status-traders').attr('title', '交易员');

				} else { // 跟随者
					role(accountRole, id1);
					// 是否显示交易信息
					showTrade(pc_userinfo.IsShowTrade, '个人简介：', pc_userinfo.Introduction, info);
					$('.card-userType').addClass('status-investors').attr('title', '跟随者');
				}
				tempHeight = bigWrap.height();
				getPersonCardPosition(bigWrap, pageX, pageY);
				bigWrap.show(100);
			}
		}
	}

	function getPersonCardPosition(bigWrap, x, y) {
		currentCard = $('.personcard-content');
		var clientHeight = document.documentElement.clientHeight;
		var popcardHeight = $('.personcard-content').height() + 15;
		if(tempHeight !== popcardHeight) {
			popcardHeight = tempHeight + 15;
		}
		var top = 0;
		var left = x - 10;

		if(clientHeight > popcardHeight) {
			if(y > popcardHeight) {
				top = y - popcardHeight + $(document).scrollTop();
				confirmPosition('t', 'b', top, left);
			} else if((clientHeight - y - personHeight) > popcardHeight) {
				// 这里应该再加一个判断，右上还是右下还是右中
				top = y + personHeight + $(document).scrollTop();
				confirmPosition('b', 't', top, left);
			} else {
				top = (clientHeight / 2) - (popcardHeight / 2) + $(document).scrollTop();
				left = x + 100;
				confirmPosition('b', 't', top, left);
			}
		} else {
			left = x + personWidth + 7; // 7是箭头的宽
			confirmPosition('b', 't', $(document).scrollTop(), left);
		}
	}

    // 鼠标移除方法
	function leave() {
	    clearTimeout(hoverDelay);
	    temp = userId;
	    if (!isHover) {
	        clearTimeout(showHoverCard);
	    } else if (currentCard) {
	        removeCard();
	        currentCard.hover(function () {
	            clearTimeout(removeHoverCard);
	            $('.privateLetter').click(function () {
	                bigWrap.hide();
	                showAnHideBox("send-box_v1", pc_userinfo.UserId, pc_userinfo.NickName);
	            });
	            // 取消关注弹出层
	            var myTimer = "";
	            $('.drop_icon').hover(function () {
	                clearTimeout(myTimer);
	                $('.drop_icon').siblings('.drop_menu_list').show();
	            }, function () {
	                var that = $(this);
	                myTimer = setTimeout(function () {
	                    that.siblings('.drop_menu_list').hide();
	                }, 200);
	            });
	            $('.drop_menu_list').hover(function () {
	                clearTimeout(myTimer);
	                $(this).find('a').click(function () {
	                    bigWrap.hide();
	                    confirmBox('确定要取消关注吗?', attentionUser, pc_userinfo.UserId);
	                });
	            }, function () {
	                var that = $(this);
	                myTimer = setTimeout(function () {
	                    that.hide();
	                }, 200);
	            });
	        }, function () {
	            removeCard();
	        });
	    }
	    isHover = false;
	}
}

// 官方V 蓝V
function role(roleType, id) {
	if(roleType >= 2) { // 蓝V
		$('.multi-account').hide();
		bigWrap.addClass('has_official_card');
		$('.mask').append($('<div>').addClass('authenticate_msg').html('<i class="icon v-official"></i>' + pc_userinfo.Certifications));
		$('.focus_num').attr('href', "/person/analyst/" + id + "?tab=1");
		$('.fans_num').attr('href', "/person/analyst/" + id + "?tab=2");
		// roleType=6机构
		if(roleType == 6) {
			$('.focus_num').attr('href', "/person/organization/" + id + "?tab=1");
			$('.fans_num').attr('href', "/person/organization/" + id + "?tab=2");
		}
	} else if(roleType == 1) { // 黄V
		$('.multi-account').hide();
		bigWrap.addClass('has_official_card');
		$('.mask').append($('<div>').addClass('authenticate_msg').html('<i class="i_certification"></i>'));

		$('.focus_num').attr('href', "/person/official/" + id + "?tab=1");
		$('.fans_num').attr('href', "/person/official/" + id + "?tab=2");
	}
}

function showTrade(trade, txt, txtInfo, div) {
	if(trade) {
		// 个人简介
		$('.mask').append(div.addClass('intro W_autocut').html(txt + txtInfo));
		createDom();
	} else {
		$('.person_follow').before(div.addClass('person_intro').html(txt + txtInfo));
	}
}

function confirmPosition(remove, add, top, left) {
	bigWrap.find('.box_arrow').removeClass('box_arrow_' + remove).addClass('box_arrow_' + add);
	bigWrap.css('top', top).css('left', left);
}

// 创建ulDOM节点
function createDom() {
	$('.person-foot').addClass('numrow3');

	// 创建文档片段存放dom
	var liFrag = document.createDocumentFragment();

	// 数值存放到数组方便遍历取值
	var ulTxt = ['收益率', '订单数'];
	var upROI = pc_userinfo.ROI.toFixed(2); // 跟随获利取两位小数
	var ulNum = [upROI + '%', pc_userinfo.Orders];

	// 跟随者有值
	if(pc_userinfo.UserType === 2) {
		ulTxt.push('跟随获利');
		ulNum.push('$' + pc_userinfo.FollowProfit);
		$('.person-foot').attr('class', 'person-foot numrow3');
	}
	if(pc_userinfo.UserType === 1) {
		ulTxt.unshift('跟随获利');
		ulNum.unshift('$' + pc_userinfo.FollowProfit);
		ulTxt.push('交易周期');
		ulNum.push(pc_userinfo.Weeks + '周');
		$('.person-foot').attr('class', 'person-foot numrow4');
	}

	// 动态生成ul
	var ulNode = document.createElement('ul');
	ulNode.setAttribute('class', 'numrow-list');

	for(var i = 0; i < ulTxt.length; i++) {
		var liNode = document.createElement('li');
		var divNode = document.createElement('div');
		divNode.setAttribute('class', 'numrow_block');

		var spanNode = document.createElement('span');
		spanNode.setAttribute('class', 'txt');
		spanNode.textContent = ulTxt[i];

		var strongNode = document.createElement('strong');
		strongNode.setAttribute('class', 'num');
		strongNode.textContent = ulNum[i];

		divNode.appendChild(spanNode);
		divNode.appendChild(strongNode);

		liNode.appendChild(divNode);
		liFrag.appendChild(liNode);
	}

	ulNode.appendChild(liFrag);
	var mid = $('<div>').addClass('person-mid').append(ulNode);
	$('.person_follow').before(mid);
}

function onChangeData(id) {

    //修改微博展示页关注状态
    var appElement = document.querySelector('[ng-controller=MicroBlogCtrl]');
    var $scope = angular.element(appElement).scope();
    if ($scope != null) {
        var curPage = $scope.Pager;
        for (var i = 0; i < curPage.itemList.length; i++) {
            var cUid = curPage.itemList[i].MicroBlog.UserId;
            if (cUid == pc_userinfo.UserId) {
                curPage.itemList[i].IsAttention = !curPage.itemList[i].IsAttention;
            }
        }
        $scope.$apply();
    }

    var className = $('.interactFocus').children('span').attr('class');
    var interactSpan = $('.interactFocus').children('span');
   
    if (className == 'set_follow') {
        $('.interactFocus').attr('class', 'interactFocus interactBtn interactBtn_follow_already drop_icon');
        interactSpan.attr('class', 'follow_already').html('<i></i>已关注');
        ajax(id1);
    } else {
        $('.drop_menu_list').hide();
        $('.interactFocus').attr('class', 'interactFocus interactBtn interactBtn_follow');
        interactSpan.attr('class', 'set_follow').html('<i></i>关注');
        ajax(id1);
        
    }
}

function ajax(uid) {
	$.ajax({
		type: "get",
		url: '/account/PersonalCard/GetPersonalCard?accountIndex=' + uid,
		async: false,
		success: function(data) {
			if(data !== null) {
				pc_userinfo = data;
			}
		}
	});
}